<?php
// +----------------------------------------------------------------------
// | OpenAdmin [ 基于ThinkPHP6和Vue3后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022 OpenAdmin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (https://gitee.com/open_admin/OpenAdmin/blob/master/LICENSE)
// +----------------------------------------------------------------------
// | 作者: About 
// +----------------------------------------------------------------------
// | 修改时间:2022/8/23-23:54
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\utils;

use app\common\model\system\MenuModel;

class CreateRouteUtils
{
    /**
     * 通过菜单数据自动生成后端路由表
     * @return false|int
     */
    public static function Admin(): false|int
    {
        $route_file = root_path() . 'app\admin\route' . DIRECTORY_SEPARATOR . 'admin.php';
        $context    = '<?php' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= '// | OpenAdmin [ 基于ThinkPHP6和Vue3后台管理系统 ]' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= '// | Copyright (c) 2022 OpenAdmin All rights reserved.' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= '// | Licensed (https://gitee.com/open_admin/OpenAdmin/blob/master/LICENSE)' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= '// | 作者: About ' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= '// | 修改时间:' . date_time() . '    该文件由自动生成器生成' . PHP_EOL;
        $context    .= '// +----------------------------------------------------------------------' . PHP_EOL;
        $context    .= 'use think\facade\Route;' . PHP_EOL . PHP_EOL;
        $context    .= "Route::group(function() {" . PHP_EOL;
        try {
            $menu = MenuModel::where('type', '<>', 1)->select()->toArray();
            foreach ($menu as $list) {
                $route_rul = str_replace('/admin/', '', $list['after_route']);
                $context   .= "    Route::rule('{$route_rul}', '{$list['controller']}', '" . strtoupper($list['methods']) . "');//{$list['name']}" . PHP_EOL;
            }

            $context .= "})->middleware('check');" . PHP_EOL;
            $context .= "Route::miss('Index/index/miss');" . PHP_EOL;
            return file_put_contents($route_file, $context);
        } catch (\Exception $e) {
            file_put_contents($route_file, $e->getMessage());
            return false;
        }
    }
}